<?php
/**
 * Created by PhpStorm.
 * User:吴鑫
 */

namespace backend\service;

use common\models\Store;
use yii\db\Query ;
use Yii ;
use yii\helpers\ArrayHelper;

class StoreService
{

    /**
     * 查找所有门店 放入缓存中
     * @return array|mixed
     */
    public static function findAllStore(){
        $stores = Yii::$app->cache->get("store_list") ;
        if(!empty($stores)){
            return $stores ;
        }

        $query = new Query();

        $query->select('*')
                ->from(Store::tableName())
                ->orderBy("id desc") ;

        $stores = $query->all() ;

        if(!empty($stores)){
            Yii::$app->cache->set("store_list",$stores,1800) ;
        }

        return $stores ;
    }

    /**
     * 按门店编号查找门店名称
     * @param $storeCode
     * @return array
     */
    public static function findStoreByCode($storeCode){
        $stores = self::findAllStore();
        if(empty($stores)){
            return "未知" ;
        }

        $data = ArrayHelper::index($stores,"store_code") ;
        $store_name = empty($data[$storeCode]['store_name'])?"未知":$data[$storeCode]['store_name'] ;
        return $store_name ;
    }

    /**
     * 按门店编号组成新的门店数组
     * @return array
     */
    public static function findAllStoreByCode(){
        $stores = self::findAllStore();
        if(empty($stores)){
            return [] ;
        }

        $data = ArrayHelper::index($stores,"store_code") ;
        return $data ;
    }

    /**
     * 门店信息数据 门店编号=>门店名称
     * @return array
     */
    public static function getStore($all=null){
        $stores = self::findAllStore();
        if(empty($stores)){
            return [] ;
        }

        if(!empty($all)){
            $data["-1"] = "全部" ;
        }else{
            $data = [] ;
        }
        foreach($stores as $key=>$val){
            $data[strval($val['store_code'])] = $val['store_name'];
        }
//        $data = ArrayHelper::map($stores, 'store_code', 'store_name');
        return $data ;
    }

}